package com.wxy.school.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxy.school.common.R;
import com.wxy.school.dto.DishDto;
import com.wxy.school.entity.Category;
import com.wxy.school.entity.Dish;
import com.wxy.school.entity.DishFlavor;
import com.wxy.school.entity.Shop;
import com.wxy.school.service.CategoryService;
import com.wxy.school.service.DishFlavorService;
import com.wxy.school.service.DishService;
import com.wxy.school.service.ShopService;
import com.wxy.school.utils.BaseContext;
import com.wxy.school.utils.OSSUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("school/dish")
@Slf4j
@RestController
public class DishController {

    @Resource
    private DishService dishService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private ShopService shopService;

    @Resource
    private DishFlavorService dishFlavorService;

    /**
     * @description: 获取菜品列表
     * @author: 王祥宇
     * @param: pageNum
     * @param: pageSize
     * @param: qurey
     * @return: com.wxy.school.common.R<com.baomidou.mybatisplus.extension.plugins.pagination.Page>
     */
    @GetMapping("/getDishList")
    public R<Page> page(int pageNum, int pageSize, String qurey, Long shopid){
        //构建Dish分页查询器
        Page<Dish> page = new Page<>(pageNum, pageSize);
        //创建DishDto分页查询器
        Page<DishDto> dishDtoPage = new Page<>();
        //构建查询条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(qurey), Dish::getDishName, qurey);
        if (shopid != null){
            lambdaQueryWrapper.eq(Dish::getShopId, shopid);
        }
        lambdaQueryWrapper.orderByDesc(Dish::getRate);
        //执行查询
        dishService.page(page, lambdaQueryWrapper);
        //将查询结果拷贝给DishDto，除了records里面的内容
        BeanUtils.copyProperties(page, dishDtoPage, "records");
        //拿到records里的内容
        List<Dish> records = page.getRecords();
        //使用Stream流对records里面的数据进行处理后在返回给dishDtoPage
        List<DishDto> list = records.stream().map((item) -> {
            //创建DishDto对象
            DishDto dishDto = new DishDto();
            //将item属性拷贝给DishDto
            BeanUtils.copyProperties(item, dishDto);
            //获取菜品分类的id
            Long categoryId = item.getCategoryId();
            //根据这个id查询category表，找到对应的分类对象
            Category category = categoryService.getById(categoryId);
            //拿到对象里面的分类名称并赋值给DishDto里面的categoryName属性
            String categoryName = category.getCategoryName();
            dishDto.setCategoryName(categoryName);
            //获取当前的商家id信息
            Long shopId = item.getShopId();
            //根据商家id查询商家信息
            Shop shop = shopService.getById(shopId);
            //将商家信息里面的商家名称信息赋值给disDto对象中的shopName属性
            dishDto.setShopName(shop.getShopName());
            //获取当前菜品的id
            Long dishId = item.getId();
            //构建查询器查询当前菜品id关联的口味数据
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(DishFlavor::getDishId, dishId);
            //将查询到的口味信息赋值给dishFlavoreList集合
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper1);
            //将口味信息列表赋值给dishDto对象中的dishFlavore属性
            dishDto.setDishFlavore(dishFlavorList);
            //返回dishDto对象
            return dishDto;
        }).collect(Collectors.toList());
        //将处理好的records数据赋值给DishDtoPage
        dishDtoPage.setRecords(list);
        //返回dishDtoPage对象
        return R.success(dishDtoPage);
    }

    /**
     * @description: 根据店铺id获取所有菜品分类列表
     * @author: 王祥宇
     * @return: com.wxy.school.common.R<java.util.List>
     */
    @GetMapping("/getCategoryList/{shopId}")
    public R<List> getCategoryList(@PathVariable Long shopId){
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Category::getShopId, shopId);
        List<Category> categoryList = categoryService.list(lambdaQueryWrapper);
        return R.success(categoryList);
    }

    /**
     * @description: 获取商家列表信息
     * @author: 王祥宇
     * @return: com.wxy.school.common.R<java.util.List>
     */
    @GetMapping("/getShopList")
    public R<List> getShopList(){
        List<Shop> shopList = shopService.list();
        return R.success(shopList);
    }

    /**
     * @description: 添加菜品信息
     * @author: 王祥宇
     * @param: dishDto
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @PostMapping("/addDish")
    public R<String> addDish(@RequestBody DishDto dishDto){
        //创建Dish对象
        Dish dish = new Dish();
        //将dishDto中的数据拷贝到dish中，除了username属性
        BeanUtils.copyProperties(dishDto, dish, "userName");
        //将登陆用户存到线程中
        BaseContext.setThreadLocal(dishDto.getUserName());
        //构建查询器根据菜品名称进行查询，并将查询结果赋值给d对象
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getDishName, dishDto.getDishName());
        List<Dish> dishList = dishService.list(lambdaQueryWrapper);
        if (!dishList.isEmpty()){
            for (Dish d : dishList) {
                //判断该菜品是否已存在
                if (d.getShopId().equals(dishDto.getShopId())) {
                    if (d.getCategoryId().equals(dishDto.getCategoryId())) {
                        return R.error("菜品已存在");
                    } else {
                        //满足条件则将菜品信息进行保存
                        dishService.save(dish);
                        //获取保存的菜品信息id
                        Long id = dish.getId();
                        //获取dishFlavore属性中的口味信息并赋值给flacors集合
                        List<DishFlavor> flavors = dishDto.getDishFlavore();
                        //循环遍历集合
                        for (DishFlavor flavor : flavors) {
                            //设置集合里面flavors对象的菜品id属性
                            flavor.setDishId(id);
                            //保存菜品口味信息
                            dishFlavorService.save(flavor);
                        }
                    }
                }else {
                    //满足条件则将菜品信息进行保存
                    dishService.save(dish);
                    //获取保存的菜品信息id
                    Long id = dish.getId();
                    //获取dishFlavore属性中的口味信息并赋值给flacors集合
                    List<DishFlavor> flavors = dishDto.getDishFlavore();
                    //循环遍历集合
                    for (DishFlavor flavor : flavors) {
                        //设置集合里面flavors对象的菜品id属性
                        flavor.setDishId(id);
                        //保存菜品口味信息
                        dishFlavorService.save(flavor);
                    }
                }
            }
        }else {
            //满足条件则将菜品信息进行保存
            dishService.save(dish);
            //获取保存的菜品信息id
            Long id = dish.getId();
            //获取dishFlavore属性中的口味信息并赋值给flacors集合
            List<DishFlavor> flavors = dishDto.getDishFlavore();
            //循环遍历集合
            for (DishFlavor flavor : flavors) {
                //设置集合里面flavors对象的菜品id属性
                flavor.setDishId(id);
                //保存菜品口味信息
                dishFlavorService.save(flavor);
            }
        }
        return R.success("菜品添加成功");
    }

    /**
     * @description: 修改菜品信息
     * @author: 王祥宇
     * @param: dishDto
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @PutMapping("/updateDish")
    public R<String> update(@RequestBody DishDto dishDto){
        //创建Dish对象
        Dish dish = new Dish();
        //将dishdto中除了categoryName之外的其他数据拷贝给dish对象
        BeanUtils.copyProperties(dishDto, dish, "categoryName,userName");
        //将登陆用户保存到线程中
        BaseContext.setThreadLocal(dishDto.getUserName());
        //获取当前菜品id
        Long dishId = dishDto.getId();
        //根据菜品id查询菜品口味信息并赋值给dishFlavoreList1集合
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
        List<DishFlavor> dishFlavorList1 = dishFlavorService.list(lambdaQueryWrapper);
        //判断菜品口味信息是否存在，若存在则删除，若不存在则直接存储
        if (!dishFlavorList1.isEmpty()){
            //根据菜品口味id将数据库中原有的菜品口味信息删除
            dishFlavorService.removeBatchByIds(dishFlavorList1);
        }
        //获取前端传递的最新的口味列表信息
        List<DishFlavor> dishFlavorList = dishDto.getDishFlavore();
        //循环遍历集合
        for (DishFlavor flavor : dishFlavorList){
            //设置集合里面flavors对象的菜品id属性
            flavor.setDishId(dishId);
            //保存菜品口味信息
            dishFlavorService.save(flavor);
        }
        Dish dish1 = dishService.getById(dishDto.getId());
        int flag = dishDto.getDishPrice().compareTo(dish1.getDishPrice());
        if (flag < 0){
            dish.setOldPrice(dish1.getDishPrice());
        }
        //保存更过的最新的菜品信息
        dishService.updateById(dish);
        return R.success("菜品信息修改成功");
    }

    /**
     * @description: 删除菜品信息
     * @author: 王祥宇
     * @param: id
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable Long id){
        dishService.removeById(id);
        return R.success("菜品删除成功");
    }

    /**
     * @description: 批量删除菜品信息
     * @author: 王祥宇
     * @param: ids
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @DeleteMapping("/deleteList")
    public R<String> deleteList(@RequestParam(value = "ids") List<Long> ids){
        // 根据前端传来的id列表查询所有的菜品信息
        List<Dish> dishList = dishService.listByIds(ids);
        // 循环遍历所有的菜品信息 并调用imageController中的deleteImages方法删除对应的菜品图片
        for (Dish dish : dishList) {
            OSSUtils.deleteFile(dish.getDishImage());
        }
        dishService.removeByIds(ids);
        return R.success("批量删除成功");
    }

    /**
     * @description: 批量启售停手菜品
     * @author: 王祥宇
     * @param: dishDtoList
     * @return: com.wxy.school.common.R<java.lang.String>
     */
    @PutMapping("/updateList")
    public R<String> updateList(@RequestBody List<DishDto> dishDtoList){
        //使用stream流将dishDtoList里面的数据拷贝给创建的dish对象中
        List<Dish> dishList = dishDtoList.stream().map((item) -> {
            Dish dish = new Dish();
            //将dishDtoList中的属性拷贝给dish对象
            BeanUtils.copyProperties(item, dish, "categoryName, userName");
            //将登录用户存到线程中
            BaseContext.setThreadLocal(item.getUserName());
            //返回dish对象
            return dish;
        }).collect(Collectors.toList());
        //执行更新操作
        dishService.updateBatchById(dishList);
        return R.success("菜品信息修改成功");
    }

    /**
     * @description: 根据菜品id查询菜品信息
     * @author: 王祥宇
     * @param: id
     * @return: com.wxy.school.common.R<com.wxy.school.dto.DishDto>
     */
    @GetMapping("/getById/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        //创建查询条件，根据id查询菜品信息
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getId, id);
        Dish dish = dishService.getOne(lambdaQueryWrapper);
        //获取菜品分类id
        Long categoryId = dish.getCategoryId();
        //根据id查询菜品分类信息
        Category category = categoryService.getById(categoryId);
        //创建DishDto对象，并将Dish中的数据拷贝给dishDto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        //设置dishDto对象中的分类名称属性
        dishDto.setCategoryName(category.getCategoryName());
        //获取商家id，并根据id查询商家信息
        Long shopId = dish.getShopId();
        Shop shop = shopService.getById(shopId);
        //设置dishDto对象中的商家名称属性
        dishDto.setShopName(shop.getShopName());
        //创建查询条件，根据dishID查询口味信息
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        //设置dishDto对象中的dishFlavore属性
        dishDto.setDishFlavore(dishFlavorList);
        //返回dishDto对象
        return R.success(dishDto);
    }
}
